/*
 * Created on Nov 10, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.wgo.preciseLite.server;

/**
 * @author nordmoen
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import test.HibernateUtil;

import com.wgo.precise.common.service.PreciseService;

public class PreciseRMIServer {

	public static final int DEFAULT_PORT = 2000;

	private final int port;
	private Registry registry;

	public PreciseRMIServer() throws RemoteException {
		this(DEFAULT_PORT);
	}

	public PreciseRMIServer(int port) throws RemoteException {
		this.port = port;
		registry = getRegistry(port);
	}

	protected void initHibernate() {
		// Trigger the Hibernate to initialize.
		HibernateUtil.getSessionFactory();
	}

	protected void bind() throws RemoteException, MalformedURLException {
		bind(new PreciseServiceHibernateImpl());
	}

	protected void bind(PreciseService service) throws RemoteException, MalformedURLException {
		PreciseService stub = (PreciseService) UnicastRemoteObject.exportObject(service, 0);
		registry.rebind("//localhost:" + port + "/precise", stub);
		Naming.rebind("//localhost:" + port + "/precise", stub);
		System.out.println("Names bound in the registry:");
		for (String name : registry.list()) {
			System.out.println(name);
		}
	}

	public static void main(String[] args) throws InterruptedException {
		try {
			PreciseRMIServer server = new PreciseRMIServer();
			server.bind();
			server.initHibernate();
			System.out.println("Precise Server ready, listening at port " + server.getPort());

		} catch (Exception e) {
			System.err.println("rmi error: " + e.toString());
			e.printStackTrace();
		}

		// Prevent VM to exit as RMI registry is a daemon.
		Object obj = new Object();
		synchronized (obj) {
			obj.wait();
		}
	}

	protected static Registry getRegistry(int port) throws RemoteException {
		Registry registry = null;
		try {
			registry = LocateRegistry.getRegistry(port);
			registry.list(); //test it
			return registry;
		} catch (RemoteException e) {
			System.out.println("Unable to find RMI registry, creating new RMI registry.");
			return registry = LocateRegistry.createRegistry(port);
		}
	}

	/**
	 * @return the port
	 */
	public int getPort() {
		return port;
	}
}